# -*- coding: utf-8 -*-

from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import logging
from logging.handlers import RotatingFileHandler
from flask import current_app, render_template
from threading import Thread
from flask_mail import Message
from flask_bootstrap import Bootstrap4

db = SQLAlchemy()
bootstrap = Bootstrap4()

# login_manager = LoginManager()
# login_manager.login_view = 'auth.login' # 登录页面的视图函数名


def setup_log(config_name):
    # server_log = TimedRotatingFileHandler('server.log','D')
    # server_log.setLevel(logging.DEBUG)
    # server_log.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))

    # error_log = TimedRotatingFileHandler('error.log', 'D')
    # error_log.setLevel(logging.ERROR)
    # error_log.setFormatter(logging.Formatter('%(asctime)s: %(message)s [in %(pathname)s:%(lineno)d]'))

    # app.logger.addHandler(server_log)
    # app.logger.addHandler(error_log)
    
    logging.basicConfig(level=config_name.LOG_LEVEL)# 设置日志的记录等级
    
    # 创建日志记录器，日志保存路径，日志文件大小，日志文件个数上限
    # 20M大小，10个文件上限
    file_log_hander = RotatingFileHandler(config_name.LOG_FILE, maxBytes=1024*1024*20, backupCount=10)
    
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    
    # 为刚创建的日志记录器设置日志记录格式
    file_log_hander.setFormatter(formatter)
    
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_hander)


def send_async_email(app, msg):
    with app.app_context():
        mail = current_app.extensions.get('mail')
        if mail:
            mail.send(msg)
            
def send_email(to, subject, template, **kwargs):    
    app = current_app._get_current_object()
    msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                  sender=app.config['MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr

